package cn.edu.niit.server.web.rest;

import static cn.edu.niit.server.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import cn.edu.niit.server.IntegrationTest;
import cn.edu.niit.server.domain.UserShare;
import cn.edu.niit.server.repository.UserShareRepository;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link UserShareResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class UserShareResourceIT {

    private static final ZonedDateTime DEFAULT_SHARE_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_SHARE_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final String ENTITY_API_URL = "/api/user-shares";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private UserShareRepository userShareRepository;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restUserShareMockMvc;

    private UserShare userShare;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static UserShare createEntity(EntityManager em) {
        UserShare userShare = new UserShare().shareTime(DEFAULT_SHARE_TIME);
        return userShare;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static UserShare createUpdatedEntity(EntityManager em) {
        UserShare userShare = new UserShare().shareTime(UPDATED_SHARE_TIME);
        return userShare;
    }

    @BeforeEach
    public void initTest() {
        userShare = createEntity(em);
    }

    @Test
    @Transactional
    void createUserShare() throws Exception {
        int databaseSizeBeforeCreate = userShareRepository.findAll().size();
        // Create the UserShare
        restUserShareMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userShare)))
            .andExpect(status().isCreated());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeCreate + 1);
        UserShare testUserShare = userShareList.get(userShareList.size() - 1);
        assertThat(testUserShare.getShareTime()).isEqualTo(DEFAULT_SHARE_TIME);
    }

    @Test
    @Transactional
    void createUserShareWithExistingId() throws Exception {
        // Create the UserShare with an existing ID
        userShare.setId(1L);

        int databaseSizeBeforeCreate = userShareRepository.findAll().size();

        // An entity with an existing ID cannot be created, so this API call must fail
        restUserShareMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userShare)))
            .andExpect(status().isBadRequest());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void getAllUserShares() throws Exception {
        // Initialize the database
        userShareRepository.saveAndFlush(userShare);

        // Get all the userShareList
        restUserShareMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(userShare.getId().intValue())))
            .andExpect(jsonPath("$.[*].shareTime").value(hasItem(sameInstant(DEFAULT_SHARE_TIME))));
    }

    @Test
    @Transactional
    void getUserShare() throws Exception {
        // Initialize the database
        userShareRepository.saveAndFlush(userShare);

        // Get the userShare
        restUserShareMockMvc
            .perform(get(ENTITY_API_URL_ID, userShare.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(userShare.getId().intValue()))
            .andExpect(jsonPath("$.shareTime").value(sameInstant(DEFAULT_SHARE_TIME)));
    }

    @Test
    @Transactional
    void getNonExistingUserShare() throws Exception {
        // Get the userShare
        restUserShareMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putNewUserShare() throws Exception {
        // Initialize the database
        userShareRepository.saveAndFlush(userShare);

        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();

        // Update the userShare
        UserShare updatedUserShare = userShareRepository.findById(userShare.getId()).get();
        // Disconnect from session so that the updates on updatedUserShare are not directly saved in db
        em.detach(updatedUserShare);
        updatedUserShare.shareTime(UPDATED_SHARE_TIME);

        restUserShareMockMvc
            .perform(
                put(ENTITY_API_URL_ID, updatedUserShare.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(updatedUserShare))
            )
            .andExpect(status().isOk());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
        UserShare testUserShare = userShareList.get(userShareList.size() - 1);
        assertThat(testUserShare.getShareTime()).isEqualTo(UPDATED_SHARE_TIME);
    }

    @Test
    @Transactional
    void putNonExistingUserShare() throws Exception {
        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();
        userShare.setId(count.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restUserShareMockMvc
            .perform(
                put(ENTITY_API_URL_ID, userShare.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userShare))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchUserShare() throws Exception {
        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();
        userShare.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserShareMockMvc
            .perform(
                put(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userShare))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamUserShare() throws Exception {
        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();
        userShare.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserShareMockMvc
            .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userShare)))
            .andExpect(status().isMethodNotAllowed());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateUserShareWithPatch() throws Exception {
        // Initialize the database
        userShareRepository.saveAndFlush(userShare);

        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();

        // Update the userShare using partial update
        UserShare partialUpdatedUserShare = new UserShare();
        partialUpdatedUserShare.setId(userShare.getId());

        partialUpdatedUserShare.shareTime(UPDATED_SHARE_TIME);

        restUserShareMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedUserShare.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedUserShare))
            )
            .andExpect(status().isOk());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
        UserShare testUserShare = userShareList.get(userShareList.size() - 1);
        assertThat(testUserShare.getShareTime()).isEqualTo(UPDATED_SHARE_TIME);
    }

    @Test
    @Transactional
    void fullUpdateUserShareWithPatch() throws Exception {
        // Initialize the database
        userShareRepository.saveAndFlush(userShare);

        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();

        // Update the userShare using partial update
        UserShare partialUpdatedUserShare = new UserShare();
        partialUpdatedUserShare.setId(userShare.getId());

        partialUpdatedUserShare.shareTime(UPDATED_SHARE_TIME);

        restUserShareMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedUserShare.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedUserShare))
            )
            .andExpect(status().isOk());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
        UserShare testUserShare = userShareList.get(userShareList.size() - 1);
        assertThat(testUserShare.getShareTime()).isEqualTo(UPDATED_SHARE_TIME);
    }

    @Test
    @Transactional
    void patchNonExistingUserShare() throws Exception {
        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();
        userShare.setId(count.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restUserShareMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, userShare.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(userShare))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchUserShare() throws Exception {
        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();
        userShare.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserShareMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(userShare))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamUserShare() throws Exception {
        int databaseSizeBeforeUpdate = userShareRepository.findAll().size();
        userShare.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserShareMockMvc
            .perform(
                patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(userShare))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the UserShare in the database
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteUserShare() throws Exception {
        // Initialize the database
        userShareRepository.saveAndFlush(userShare);

        int databaseSizeBeforeDelete = userShareRepository.findAll().size();

        // Delete the userShare
        restUserShareMockMvc
            .perform(delete(ENTITY_API_URL_ID, userShare.getId()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<UserShare> userShareList = userShareRepository.findAll();
        assertThat(userShareList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
